package com.example.video.ui;

import java.io.IOException;

import com.example.video.Config;
import com.example.video.ErrorCode;
import com.example.video.io.database.DatabaseHelper;
import com.example.video.util.Preference;

import vn.tdx.androidlibs.util.DatabaseUtils;
import vn.tdx.androidlibs.util.FileUtils;
import vn.tdx.androidlibs.util.NetworkUltis;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.AsyncTaskLoader;

public class SplashActivity extends Activity{
	private static final String TAG="SplashActivity";
	
	private static final int EVENT_STARTAPP=0;
	private static final int EVENT_CHECK_YOUTUBE=EVENT_STARTAPP+1;
	private static final int EVENT_CHECK_VERSION=EVENT_CHECK_YOUTUBE+1;
	private static final int EVENT_UPDATE_DATABASE=EVENT_CHECK_VERSION+1;
	private static final int EVENT_ERROR=EVENT_UPDATE_DATABASE+1;
	private static final int EVENT_CHECK_INTERNET=EVENT_ERROR+1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//copy database
		DatabaseUtils.copyAssetToDatabase(getApplicationContext(), "video.db",DatabaseHelper.DB_NAME);
		onEvent(EVENT_STARTAPP, 1);
	}
	
	private void onEvent(int event,int errorCode){
		switch (event) {
		case EVENT_STARTAPP:
			Intent intent=new Intent(this,MainActivity.class);
			startActivity(intent);
			break;
		case EVENT_CHECK_YOUTUBE:
					
			break;
		case EVENT_CHECK_VERSION:
			
			break;
		case EVENT_CHECK_INTERNET:
			if(NetworkUltis.isConnected(getApplicationContext()))
				onEvent(EVENT_CHECK_YOUTUBE, -1);
			else
				onEvent(EVENT_ERROR, ErrorCode.ERROR_NOTCONNECTED);
			break;
		case EVENT_UPDATE_DATABASE:
	
			break;
		case EVENT_ERROR:
			
			break;

		default:
			break;
		}
	}
	
	private static class LoadData extends AsyncTaskLoader<Integer>{

		public LoadData(Context context) {
			super(context);
		}

		@Override
		public Integer loadInBackground() {
			//check internet
			if(!NetworkUltis.isConnected(getContext()))
				return ErrorCode.ERROR_NOTCONNECTED;
			
			//check youtube
			
			//check version
			String dbUrl="";
			try {
				String content=FileUtils.readFile(Config.CONFIG_URL);
				String[] values=content.split("|");
				String serverVersion=values[0];
				dbUrl=values[1];
				String clientVersion=Preference.getVersionDB(getContext());
				if(!serverVersion.equals(clientVersion)){
					//update db
				}else{
					
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
			return null;
		}
	}
}

